import ctypes
if ctypes.windll.kernel32.GetConsoleWindow() !=0:
    ctypes.windll.user32.ShowWindow(ctypes.windll.kernel32.GetConsoleWindow(),0)
    ctypes.windll.kernel32.CloseHandle(ctypes.windll.kernel32.GetConsoleWindow(),0)

from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.header import Header
from smtplib import SMTP_SSL
from threading import Thread
from time import sleep
import shutil
import signal
import os,sys
import re
try:
    import win32gui, win32con, win32com.client
    from PIL import Image
    from mss import mss
    import numpy as np
    import cv2
except:
    os.system('pip install mss numpy pillow opencv-python pywin32')
    import win32gui, win32con, win32com.client
    from PIL import Image
    from mss import mss
    import numpy as np
    import cv2


def signal_handler(signal, frame):
    try:
        global smtp
        smtp.close()
    except:pass
    try:
        os.remove('4.monitor-1.png')
        os.remove('4.this.png')
        os.remove('4.this.last.png')
    except:pass
    sys.exit(0)

def _window_enum_callback(hwnd, wildcard):
    if re.match(wildcard, str(win32gui.GetWindowText(hwnd))) is not None:
        win32gui.BringWindowToTop(hwnd)
        shell = win32com.client.Dispatch("WScript.Shell")
        shell.SendKeys('%')
        win32gui.SetForegroundWindow(hwnd)
        win32gui.ShowWindow(hwnd, win32con.SW_MAXIMIZE)

signal.signal(signal.SIGINT, signal_handler)

sleep(240)
while True:
    try:
        from pynput.mouse import Button, Controller
        
        Controller().position = (690, 410)
        Controller().click(Button.left)
        Controller().click(Button.left)
        sleep(60)
        Controller().position = (150, 300)
        Controller().click(Button.left)
        sleep(3)
        
        break
    except:
        os.system("pip install pynput")
        
print("正在每60秒检测一次课")

fa = os.path.dirname(os.path.abspath(__file__)) + '//' + '4.monitor-1.png'
fc = os.path.dirname(os.path.abspath(__file__)) + '//' + '4.this.last.png'
f_1 = os.path.dirname(os.path.abspath(__file__)) + '//' + '4.1.png'
f_2 = os.path.dirname(os.path.abspath(__file__)) + '//' + '4.2.png'
f_4 = os.path.dirname(os.path.abspath(__file__)) + '//' + '4.4.png'
f_1_cv = cv2.imread(f_1, 0)
f_2_cv = cv2.imread(f_2, 0)
f_4_cv = cv2.imread(f_4, 0)
f_2_cv_w, f_2_cv_h = f_2_cv.shape[::-1]
f_4_cv_w, f_4_cv_h = f_4_cv.shape[::-1]

try:
    os.remove(fa)
    os.remove(fc)
except:
    pass

window_name = "Oracle VM VirtualBox"

while True:
    
    try:
        win32gui.EnumWindows(_window_enum_callback, ".*%s.*" %window_name)
    except:pass

    mss().shot(output=fa)

    if not os.path.exists(fc):
        shutil.copy(fa, fc)
        continue
    
    img_rgb = cv2.imread(fa, 0)

    retu = cv2.matchTemplate(img_rgb, f_1_cv, cv2.TM_CCOEFF_NORMED)
    index = np.where(retu > 0.9)

    if index[0].size > 0 :

        for i in zip(*index[::-1]):

            click_posi = i

        Controller().position = (click_posi[0], click_posi[1])
        Controller().click(Button.left)

        retu = cv2.matchTemplate(img_rgb, f_4_cv, cv2.TM_CCOEFF_NORMED)
        index = np.where(retu > 0.9)

        if index[0].size > 0:

            for i in zip(*index[::-1]):

                click_posi = i

            Controller().position = (click_posi[0]+f_4_cv_w/2, click_posi[1]+f_4_cv_h/2)
            Controller().click(Button.left)

        # cv2.imwrite(fa, img_rgb)

        email_receiver='2907821379@qq.com'
        email_title='课！'
        email_content='已经开始录制'
        try:
            os.system(r'start /d "C:\Program Files\obs-studio\bin\64bit" /b obs64.exe /c --startrecording')
        except:
            email_title+='Obs启动失败！'

        try:
            os.system(r'start /d "' + os.path.dirname(os.path.abspath(__file__)) + r'" /b 3.dontstuck.py' )
        except:
            email_title+='Dontstuck启动失败！'

        smtp_serv = 'smtp.qq.com'
        smtp_port = 465
        smtp_addr = '2674075194@qq.com'
        smtp_name = '2674075194'
        smtp_pass = 'pfoictixwhxidihh'
        
        smtp = SMTP_SSL(smtp_serv, smtp_port)
        smtp.set_debuglevel(0)
        smtp.ehlo(smtp_serv)
        smtp.login(smtp_name,smtp_pass)
        msg = MIMEMultipart()
        msg["Subject"]=email_title
        msg["From"]=smtp_addr
        msg["To"]=email_receiver
        
        file_attach=fa
        with open(file_attach, "rb") as f:
            part = MIMEApplication(f.read(), Name=os.path.basename(file_attach))
            msg.attach(part)
        
        if email_title!='课！':
            smtp.sendmail(smtp_addr, email_receiver, msg.as_string())
        
        smtp.close()
    
    f_2_cv_retu = cv2.matchTemplate(img_rgb, f_2_cv, cv2.TM_CCOEFF_NORMED)
    f_2_cv_index = np.where(f_2_cv_retu > 0.9)
    
    if f_2_cv_index[0].size > 0:

        for i in zip(*f_2_cv_index[::-1]):
            i_retu = i

        Controller().position = (i_retu[0]+0.5*f_2_cv_w+270, i_retu[1]+0.5*f_2_cv_h)
        Controller().click(Button.left)

        try:
            os.system('wmic process where name="obs64.exe" call terminate')
        except:
            pass

    sleep(60)
    shutil.copy(fa, fc)


